<?php

/**
 * 新炫舞宝贝评选2016
 * User: huy
 * Date: 2016/7/4
 * Time: 16:36
 */
class IndexControl extends Control{
    private $model;
    private $time1    = '2016-07-20 00:00:00';   //开始
    private $time2    = '2016-08-01 00:00:00';   //中间投票时间
    private $time3    = '2016-08-31 23:59:59';   //结束
    private $zone_arr = '';    //存大区的名称
    private $uin      = '';
    private $zoneid   = '';
    private $hcoin    = 0;
    private $gamecoin = 2000;//投票每一票消耗的游戏币5000
    private $limit    = 10;   //每天最多投10票
    private $level    = 30;//参加活动的等级限制

    //构造函数
    function __construct(){
        parent::__construct();
        $this->actName = '新炫舞宝贝评选';
        load_config('commonMain/onload');
        $this->zone_arr = get_dmz_game_zone();
        load_model(ACT_NAME . '/main');   //自己的main.mod
        $this->model = new MainModel();
        /**
         * 载入不同的控制器
         */
        //include 'iswhere.ctl.php';
        include 'isvote.ctl.php';
        include 'issign.ctl.php';
        include 'userinfo.ctl.php';
        include 'sendgift.ctl.php';
        //重新设置活动时间（用于外网、预发布环境）
        if(file_exists(APPLICATION_ROOT . '/config/basic.cfg.php')){
            //include文件的路径，$BasicCFG就存下了.php return 的数组
            $BasicCFG = include_once APPLICATION_ROOT . '/config/basic.cfg.php';
            if(!empty($BasicCFG[YEAR][ACT]['time1']) && !empty($BasicCFG[YEAR][ACT]['time2']) && !empty($BasicCFG[YEAR][ACT]['time3']) && !empty($BasicCFG[YEAR][ACT]['level']) && !empty($BasicCFG[YEAR][ACT]['gamecoin']) && !empty($BasicCFG[YEAR][ACT]['money'])){
                $this->time1    = $BasicCFG[YEAR][ACT]['time1'];
                $this->time2    = $BasicCFG[YEAR][ACT]['time2'];
                $this->time3    = $BasicCFG[YEAR][ACT]['time3'];
                $this->level    = $BasicCFG[YEAR][ACT]['level'];
                $this->gamecoin = $BasicCFG[YEAR][ACT]['gamecoin'];
                $this->money    = $BasicCFG[YEAR][ACT]['money'];
            }
        }
    }

    /**
     * 首页
     */
    public function index(){
        //echo DOMAIN_URL.'/upload/';die;
        //1.推荐的4条记录
        //order_by推荐排序，默认50，排序值为1~4为首页推荐：运营后台配置
        $ret = $this->model->get_item('bbpx2016_userinfo', 'uin,zone_id,role_name,vip,vip_status,vote,pic1,pic2,pic3,brand', 'status=5', ' order by order_by asc limit 4');
        if(!empty($ret)){
            foreach($ret as &$it){
                $it['zone_id'] = $this->zone_arr[$it['zone_id']];  //获取大区名称
            }
        }
        $view['ret']     = $ret;   //4条推荐 记录
        $view['money']   = isset($_SESSION['money']) ? $_SESSION['money'] : 0;
        $view['sendurl'] = 'http://act.xx5.com/2016/bbpx2016';
        $view['content'] = '想成为夏日梦之星吗？那就来参加51新炫舞7周年夏日梦之星评选吧~';

        //2.首页排行榜——这里返回的直接是html
        $view['index_rank'] = $this->get_index_rank();
        if(!$this->isLogin()){                          //bbpx2016_userinfo_copy
            $list_old           = $this->model->get_item('bbpx2016_userinfo', '*', " uin={$this->uin}  limit 1");
            $view['status_old'] = $list_old[0]['status'];
            //获取玩家信息
            $userInfo             = $this->model->getGameUserInfo($this->uin, $this->zoneid);
            $zones                = get_dmz_game_zone();
            $_SESSION['roleName'] = $userInfo['RoleName'];
            $_SESSION['zoneName'] = $zones[$_SESSION[DOMAIN_ACT_ZONEID_KEY]];
        }
        //3.投票排行榜，开始投票以后进行显示
        $view['show_rank'] = 0;
        $time              = time();
        if($time > strtotime($this->time2)){
            //进入投票时间
            $view['show_rank'] = 1;
        }
        load_view(ACT_NAME . '/index', $view);
    }

    //奖品展示页
    public function award(){
        load_view(ACT_NAME . '/award');
    }

    //活动规则页
    public function rule(){
        //$view['sign']这个sign的作用？？
        $view['sign'] = 0;
        if(!$this->isLogin()){
            //不限制zoneid
            $list = $this->model->get_item('bbpx2016_userinfo', "uin,`status`", " uin={$this->uin}  limit 1");
            if(!empty($list)){
                $view['sign'] = 1;
            }
        }
        load_view(ACT_NAME . '/rule', $view);
    }

    /*
         * 首页前10名排行榜: 排名   玩家昵称   总票数
         */
    public function get_index_rank(){
        $r   = $this->model->get_item('bbpx2016_userinfo', '*', "status=5", "order by vote desc");  //票数递减排列
        $len = count($r);

        $html = '';
        $rank = 1;
        $i    = 0;
        if(!empty($r)){
            while($i < $len){
                if($i != 0 && $r[$i]['vote'] < $r[$i - 1]['vote']){
                    $rank++;
                }
                if($rank <= 10){
                    //	       排名                                        玩家昵称                                          总票数
                    $html .= '<li><span class="c1 up">' . $rank . '</span>' . '<span class="c2">' . $r[$i]['role_name'] . '</span>' . '<span class="c3">' . $r[$i]['vote'] . '</span></li>';
                    //<li><span class="c1 up">1</span><span class="c2">水仙花珍惜花</span><span class="c3">10000000</span></li>
                    $i++;
                }else{
                    break;
                }
            }
        }else{
            $html .= "<li></li>";
        }

        return $html;
    }
    /*
        * 玫瑰明星排名页面
        * 1.按照投票票数由多到少排列
        * 2.每页显示8个
        * 3.分页
        * 4.按照限制获取排名：昵称，时间，人气，选择大区
        *
        */
    //投票列表——明星排名页
    public function ranking(){
        $view['sign']  = 0;
        $view['f']     = 3;
        $view['money'] = 0;
        $view['roles'] = '';
        $zones         = get_dmz_game_zone();
        //$type  显示的type,1按照排名，
        $view['type'] = $type = isset($_GET['type']) ? intval($_GET['type']) : 1;

        //选择大区，默认是大区是：0
        $view['select'] = $select = isset($_GET['select']) ? intval($_GET['select']) : 0;
        if(!key_exists($select, $zones)){
            //key_exists(key,array)key是否存在array中
            //大区选择错误，大区号=0
            $select = 0;
        }
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        //$where    添加查询的限制条件
        //1.限制审核通过，status = 5
        $where = "`status`=5";

        //搜索的分区选择正确
        if($select != 0){
            //2.限制选择的大区
            $where .= ' and zone_id=' . $select;
        }

        if(!$this->isLogin()){
            $list = $this->model->get_item('bbpx2016_userinfo', "uin,`status`", " uin={$this->uin}  limit 1");
            if(!empty($list)){
                $view['sign'] = 1;  //已报名
            }
            //昵称搜索
            $view['roles'] = $roles = isset($_GET['roles']) ? urldecode($_GET['roles']) : '';
            if(!empty($roles) && $this->_strlen_utf8($roles) < 30){
                $roles = mysql_escape_string($roles);    //过滤
                //3.限制昵称
                $where .= " and role_name like '%{$roles}%'";
            }
            $view['f']     = 1;
            $view['money'] = $_SESSION['money'];
        }
        $view['rolename'] = empty($view['roles']) ? '昵称' : $view['roles'];
        //显示
        if(1 == $type){
            //==1  按照投票数来排名   显示
            $order = "order by vote desc";
        }else{
            //按照时间排序  显示
            $order = "order by create_time desc";
        }
        //test....8改为4
        $ret = $this->model->get_list_page('bbpx2016_userinfo', $where, $page, 12, $order);   //显示8条，每页
        //这里把大区名取出来有什么作用——————更新了$ret的大区，大区不是编号，而是大区名称——okok
        if(!empty($ret['rows'])){
            foreach($ret['rows'] as &$it){
                $it['zone_id'] = $this->zone_arr[$it['zone_id']];
                //$it['zone_id']存选出来的大区的名称
            }
        }

        $view['content_list'] = $ret;
        $view['sendurl']      = 'http://act.xx5.com/2016/bbpx2016';
        $view['content']      = '新炫舞宝贝评选啦~';
        load_view(ACT_NAME . '/ranking', $view);
        exit;
    }

    public function userinfo(){
        if($this->isLogin()){
            //没有登录，查看我的信息，跳转到报名页面
            header('Location:http://act.xx5.com/2016/bbpx2016/index.php?a=sign');
            exit;
        }
        $user = new UserinfoControl();
        $user->userinfo($this->uin, $this->zone_arr);
    }

    //审核通过发放  小时候萌萌哒
    public function sendgift(){
        $uin = $_GET['uin'];
        //uin in ({$uin})??    1.是：in ？   2.没有限定  zoneid
        $sendgift = new SendgiftControl();
        $sendgift->sendgift($uin);
    }

    //报名
    public function sign(){
        $sign = new IssignControl();
        if(!$this->isLogin()){
            $login = 1;  //登录了
        }else{
            $login = 0;
        }
        $sign->sign($login, $this->uin);
    }

    //再次报名
    public function resign(){
        $resign = new IssignControl();
        if(!$this->isLogin()){
            $login = 1;  //登录了
        }else{
            $login = 0;
        }
        $resign->resign($login, $this->uin);
    }

    //保存第一次报名信息
    public function save_sign(){
        $save_sign = new IssignControl();
        if(!$this->isLogin()){
            $login = 1;  //登录了
        }else{
            $login = 0;
        }
        $save_sign->save_sign($login, $this->uin, $this->zoneid);
    }

    //保存第二次报名信息
    public function resave_sign(){
        $resave_sign = new IssignControl();
        if(!$this->isLogin()){
            $login = 1;  //登录了
        }else{
            $login = 0;
        }
        $resave_sign->resave_sign($login, $this->uin, $this->zoneid);
    }

    //报名完后，开始投票,游戏币——投票
    public function vote(){
        //传过来的被投票的玩家uin
        $f_uin = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $vote  = new IsvoteControl();
        if(!$this->isLogin()){
            $login = 1;  //登录了
        }else{
            $login = 0;
        }
        $vote->vote($login, $f_uin, $this->uin, $this->zoneid);
    }

    //报名完后，送玫瑰投票
    public function buyApple(){
        $buyApple = new IsvoteControl();
        $f_uin    = isset($_POST['id']) ? intval($_POST['id']) : 0;
        //玫瑰个数
        $num = isset($_POST['num']) ? intval($_POST['num']) : 0;
        if(!$this->isLogin()){
            $login = 1;  //登录了
        }else{
            $login = 0;
        }
        $buyApple->buyApple($login, $this->uin, $this->zoneid, $f_uin, $num);
    }

    //登录判断
    private function isLogin(){
        if(empty($_SESSION['UIN']) || empty($_SESSION[DOMAIN_ACT_ZONEID_KEY])){
            return true;
        }
        $this->uin        = $_SESSION['UIN'];
        $this->zoneid     = $_SESSION[DOMAIN_ACT_ZONEID_KEY];
        $ret              = ChangeUinByZone($_SESSION['UIN'], $_SESSION[DOMAIN_ACT_ZONEID_KEY]);//大区转换
        $this->uin_new    = $ret['UIN'];
        $this->zoneid_new = $ret['ZoneID'];
        return false;
    }

    //登录处理
    public function save(){
        load_library('pub:core/FOPassPort', false);

        if(array_key_exists('jumpto', $_GET)){
            $jumpto = urldecode(htmlspecialchars_decode(($_GET['jumpto'])));
        }else{
            $jumpto = DOMAIN_URL;
        }
        if(stripos($jumpto, 'xx5.com') === false){
            die('error');
        }

        $logouturl = 'http://passport.xx5.com/logout.php?gourl=' . urlencode(DOMAIN_URL);
        if(empty($_SESSION['UIN']) || empty($_SESSION['LoginUser'])){
            session_unset();
            dumpErrorCode('登录失败，请重试！', $logouturl);
        }

        header("Location:" . $jumpto);
        exit;
    }

    /**
     * 选区
     * Enter description here ...
     */
    public function saveSelectZone(){
        if(!check_post_from()){
            echo json_encode(array('success' => 2, 'msg' => '选区出错~'));
            return;
        }

        if(empty($_SESSION['UIN'])){
            echo json_encode(array('success' => 0, 'msg' => '请登录~'));
            return;
        }else{
            $gamezone = isset($_POST['k']) ? intval($_POST['k']) : 0;
            $zone     = get_dmz_game_zone();
            if(!isset($gamezone) || !array_key_exists($gamezone, $zone)){
                echo json_encode(array('success' => 2, 'msg' => '登录失败，请重试~'));
                return;
            }
            $_SESSION[DOMAIN_ACT_ZONEID_KEY] = $gamezone;

            $result = $this->model->getGameUserInfo($_SESSION['UIN'], $_SESSION[DOMAIN_ACT_ZONEID_KEY]);

            if(empty($result)){
                echo json_encode(array('success' => 2, 'msg' => '你选择分区未创建角色，请重新选择！'));
                return;
            }

            $_SESSION['Gender']   = $result['Gender'];
            $_SESSION['RoleName'] = $result['RoleName'];
            $_SESSION['Level']    = $result['Level'];
            $_SESSION['money']    = $result['Money'];
            $_SESSION['IP']       = get_client_ip_from_ns(true);
            echo json_encode(array('success' => 1, 'msg' => '成功！'));
        }
        return;
    }

    /*
     * 处理退出登录
     */
    public function logout(){
        session_unset();
        session_destroy();
        $gourl = empty($_GET["jumpto"]) ? "" : $_GET["jumpto"];
        $gourl = empty($gourl) ? DOMAIN_URL : $gourl;
        $gourl = urlencode(htmlspecialchars_decode($gourl));
        header("Location: http://passport.xx5.com/logout.php?gourl=" . $gourl);
        flush();
        exit;
    }

    //计算多少个字数    ord()计算汉字的assII值
    public function _strlen_utf8($str){
        if(function_exists('mb_strlen')){
            return mb_strlen($str, 'utf8');
        }
        $i     = 0;
        $count = 0;
        $len   = strlen($str);
        while($i < $len){
            $chr = ord($str[$i]);
            $count++;
            $i++;
            if($i >= $len){
                break;
            }

            if($chr & 0x80){
                $chr <<= 1;
                while($chr & 0x80){
                    $i++;
                    $chr <<= 1;
                }
            }
        }
        return $count;
    }

    //奖励页面
    public function prize(){
        load_view(ACT_NAME . '/prize');
    }

    //获取玩家游戏账单  大喇叭和魅力值转换票数
    public function getGamersInfo(){
        sleep(600);  //延迟5分钟执行
        echo date('Y-m-d H:i:s', time()) . "\n";
        $time2   = '2016-08-01 01:01:00';   //投票活动未开始时间
        $time3   = '2016-09-01 00:11:00';   //活动结束时间  魅力值和喇叭数延迟一个小时入库
        $nowTime = date('Y-m-d H:i:s', time());
        if($nowTime <= $time3 && $nowTime >=$time2){  //当前时间小于活动时间   大于投票开始时间
            $date      = date('Ymd', time());
            $t1        = date('Y-m-d H:i:s', time() - 4200); //上一个小时3600+10分钟延迟
            $t2        = date('Y-m-d H:i:s', time());
            $allGamers = $this->model->get_item('bbpx2016_userinfo', "uin,zone_id");
            //需要把uin,zone_id转换
            foreach($allGamers as $k => $v){
                $ret          = ChangeUinByZone($v['uin'], $v['zone_id']);//大区转换
                $meili        = $this->model->getBillValue($date, $ret['UIN'], $ret['ZoneID'], 26, 'value', 'bill', $t1, $t2);
                $laba         = $this->model->getBillValue($date, $ret['UIN'], $ret['ZoneID'], 25, 'value', 'bill', $t1, $t2);
                $overplusInfo = $this->model->getRow('bbpx2016_overplus', "where uin={$v['uin']}", 'overplus_vote'); //获取剩余表是否有玩家剩余信息
                if(!empty($overplusInfo)){
                    $meili = $overplusInfo['overplus_vote'] + $meili;
                }
                if($meili > 2000){
                    $ticket       = floor($meili / 2000);
                    $overplus     = $meili - 2000 * $ticket;   //这个小时剩余的魅力值
                    $overplusInfo = $this->model->getRow('bbpx2016_overplus', "where uin={$v['uin']}", 'overplus_vote'); //剩余表是否有玩家剩余信息
                    if(empty($overplusInfo)){
                        $para = array(
                            'uin'           => $v['uin'],
                            'zone_id'       => $v['zone_id'],
                            'overplus_vote' => $overplus,
                            'createtime'    => date('Ymd', time())
                        );
                        $this->model->insert_datas('bbpx2016_overplus', $para);
                    }else{ //否则有信息的话就直接修改
                        $param = array(
                            'overplus_vote' => $overplus,  //$overplusInfo['overplus_vote'] +
                            'createtime'    => date('Ymd', time())
                        );
                        $this->model->update_datas('bbpx2016_overplus', $param, "where uin={$v['uin']}");
                    }

                    $vote  = $this->model->getRow('bbpx2016_userinfo', "where uin={$v['uin']}", 'vote');
                    $vote  = $vote['vote'];
                    $param = array(
                        'vote' => $vote + $ticket,
                    );
                    $a     = $this->model->update_datas('bbpx2016_userinfo', $param, "where uin={$v['uin']}");
                    $param = array(
                        'uin'         => $ret['UIN'],
                        'zone_id'     => $ret['ZoneID'],
                        'meili_vote'  => $ticket,
                        'create_time' => date('Y-m-d H:i:s', time())
                    );
                    $b     = $this->model->insert_datas('bbpx2016_meili', $param);
                    if($a && $b){
                        echo date('Y-m-d H:i:s', time()) . $ret['UIN'] . '魅力值转换finish';
                        echo "\n";
                    }
                }
                if($laba){
                    $ticket = ($laba * 20);
                    $vote   = $this->model->getRow('bbpx2016_userinfo', "where uin={$v['uin']}", 'vote');
                    $vote   = $vote['vote'];
                    $param  = array(
                        'vote' => $vote + $ticket,
                    );
                    $a      = $this->model->update_datas('bbpx2016_userinfo', $param, "where uin={$v['uin']}");
                    $param  = array(
                        'uin'         => $ret['UIN'],
                        'zone_id'     => $ret['ZoneID'],
                        'laba_vote'   => $ticket,
                        'create_time' => date('Y-m-d H:i:s', time())
                    );
                    $b      = $this->model->insert_datas('bbpx2016_laba', $param);
                    if($a && $b){
                        echo date('Y-m-d H:i:s', time()) . $ret['UIN'] . '魅力值转换finish';
                        echo "\n";
                    }
                    echo date('Y-m-d H:i:s', time()) . $ret['UIN'] . '喇叭值转换finish';
                    echo "\n";
                }
            }
        }else{
            echo '活动结束或投票时间未开始' . "\n";
        }
    }

    //查询账单   http://act.xx5.com/2016/bbpx2016/index.php?a=billInfo
    public function billInfo(){
        $uin     = 305126315;
        $zone_id = 100;
        $date    = date('Ymd', time());
        $t1      = date('Y-m-d H:i:s', time() - 5400); //上一个小时3600
        $t2      = date('Y-m-d H:i:s', time());
        $meili   = $this->model->getBillValue($date, $uin, $zone_id, 26, 'value', 'bill', $t1, $t2);
        echo $meili;
    }
}